如何使用Java中的foreach语句来获取对象index下标 实例代码解析 |
您所在的位置:网站首页 › sql foreach的下标加1 › 如何使用Java中的foreach语句来获取对象index下标 实例代码解析 |
foreach语句是Java8提供的一个全新特性,用于遍历数组、集合等,相比for循环而言简化了不少。但是我们在遍历的同时,又想获取对象的index下标,用foreach语句是要怎么实现的呢?下面,将通过Java实例代码来为大家详细讲解。 前言在Java8中,我们经常使用lambada表达式进行foreach循环,但是常常我们在遍历List的时候想获取对象的index,但是Java8、9、10、11都没有相关的支持,同样的问题也存在于增强型for循环中,很多时候不得不含着泪以 for (int i = 0; i < list.size(); i++) 的方式写代码 我们的期望 list.foreach((item,index)->{}) //编译不通过常见的list获取index方法 for(int i=0;i) for (int i = 0; i < list.size(); i++) { }indexOf(Obj) for (Object o : list) { list.indexOf(o); //如果是Set还没有这个方法 }还有… int i = 0; for (String s : list) { i++; }很显然上述的方法并不是我们所想要的 Consumer和BiConsumer我们看个简单的例子 Consumer consumer = t -> System.out.println(t); consumer.accept("single"); BiConsumer biConsumer = (k, v) -> System.out.println(k+":"+v); biConsumer.accept("multipart","double params");输出结果: single multipart:double params 这里不难发现我们平时写的箭头函数其实是一个Consumer或者BiConsumer对象 定制Consumerforeach源码 default void forEach(Consumer |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |